package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static org.apache.ibatis.ognl.DynamicSubscript.first;

@Service
@Slf4j
@Transactional
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {

    @Autowired
    private UserService userService;

    @Autowired
    private VMService vmService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private TaskDao taskDao;

    @Autowired
    private MqttProducer mqttProducer;


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE).plusDays(1));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);


        return Pager.build(this.page(page, qw));
    }


    /**
     * 通过vo创建工单,运营和运维共用
     *
     * @param taskViewModel dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createTask(TaskViewModel taskViewModel) {
        TaskEntity task = new TaskEntity();

        //1.判断指派用户是否存在
        UserVO user = userService.getUser(taskViewModel.getUserId());
        if (user == null) {
            throw new LogicException("指定的任务执行人不存在");
        }
        task.setUserName(user.getUserName());

        //2.校验售货机状态
        VmVO vmInfo = vmService.getVMInfo(taskViewModel.getInnerCode());
        checkVmStatus(taskViewModel, vmInfo);

        //3.校验同一台设备是否有未完成同类型工单
        checkTask(taskViewModel);
        //4.属性拷贝
        BeanUtils.copyProperties(taskViewModel, task);

        //5.生成工单编号,redis实现
        String taskCode = generateTaskCode();
        task.setTaskCode(taskCode);
        task.setRegionId(vmInfo.getRegionId());
        task.setAddr(vmInfo.getNodeAddr());
        task.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        this.save(task);

        //7.如果是运营工单则创建补货单
        saveTaskDetail(taskViewModel, task);

        return true;
    }

    /**
     * 把自动创建的工单分配给当天工单量最少的用户
     * @param innerCode
     */
    @Override
    public void AutoDistributeTask(String innerCode,int type,List<TaskDetailsViewModel> details) {
        //查询售货机所在区域
        VmVO vmInfo = vmService.getVMInfo(innerCode);

        //构建基本信息
        TaskViewModel taskViewModel = new TaskViewModel();
        taskViewModel.setCreateType(VMSystem.TASK_CREATE_AUTO);
        taskViewModel.setProductType(type);
        taskViewModel.setInnerCode(innerCode);
        taskViewModel.setDesc("售货机自动上报工单");
        taskViewModel.setDetails(details);
        //1.判断是运营工单还是运维工单
        //如果是运营工单,分配给运营人员
        Object first = null;
        if (VMSystem.TASK_TYPE_SUPPLY.equals(type)){
            first = changeCacheTask(VMSystem.USER_OPERATOR,vmInfo.getRegionId(),1);
        }else {
            //如果是运维工单,分配给运营人员
            first = changeCacheTask(VMSystem.USER_REPAIRER, vmInfo.getRegionId(), 1);
        }
        //设置用户基本信息
        taskViewModel.setUserId((int)first);

        //创建工单
        createTask(taskViewModel);
    }

    /**
     * 更改缓存中的排行榜
     * @param roleCode
     */
    private Object changeCacheTask(String roleCode,Long regionId,double delta) {
        //构造key
        String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String key = "vmAutoTask." + dateStr + regionId + roleCode;
        //查询出当前区域对应的用户
        Set set = redisTemplate.opsForZSet().rangeWithScores(key, 0, -1);
        if (set == null){
            return new Object();
        }
        Object first = set.stream().findFirst().get();
        //加分
        redisTemplate.opsForZSet().incrementScore(key,first.toString(),delta);
       return first;
    }

    /**
     * 接受工单
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean acceptTask(Long taskId) {
        //1.查询工单
        TaskEntity task = getById(taskId);
        if (task == null) {
            throw new LogicException("工单不存在");
        }

        //2.判断工单状态
        //状态不是待处理,抛出异常
        if (!VMSystem.TASK_STATUS_CREATE.equals(task.getTaskStatus())) {
            throw new LogicException("工单不是待处理状态");
        }

        //修改状态为进行中
        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        updateById(task);
        return true;
    }

    /**
     * 取消工单
     *
     * @param taskId
     * @param model
     * @return
     */
    @Override
    public boolean cancelTask(Long taskId, CancelTaskViewModel model, Integer userId) {
        //1.查询工单
        TaskEntity task = getById(taskId);
        if (task == null) {
            throw new LogicException("此工单不存在");
        }
        //2.判断工单执行人是否是当前用户
        if (!userId.equals(task.getUserId())) {
            throw new LogicException("工单执行人不是当前用户");
        }

        //3.如果工单状态是已取消或者完成,抛出异常
        if (VMSystem.TASK_STATUS_CANCEL.equals(task.getTaskStatus())) {
            throw new LogicException("工单已经处于取消状态");
        } else if (VMSystem.TASK_STATUS_FINISH.equals(task.getTaskStatus())) {
            throw new LogicException("工单处于完成状态");
        }

        //4.修改工单状态为取消,记录原因
        task.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        updateById(task);

        //保存工单取消原因
        taskDao.saveCancelReason(taskId, model.getDesc());

        //更改缓存中的排行榜
        UserVO user = userService.getUser(userId);
        if (user == null){
            throw new LogicException("用户不存在");
        }
        changeCacheTask(user.getRoleCode(),user.getRegionId(),-1);

        return true;
    }

    /**
     * 完成工单
     *
     * @param taskId
     * @param userId
     * @return
     */
    @Override
    public boolean completeTask(Long taskId, Integer userId) {
        //1.查询工单
        TaskEntity task = getById(taskId);
        if (task == null) {
            throw new LogicException("此工单不存在");
        }
        //2.判断工单执行人是否是当前用户
        if (!userId.equals(task.getUserId())) {
            throw new LogicException("工单执行人不是当前用户");
        }

        //3.如果工单状态是已取消或者完成,抛出异常
        if (VMSystem.TASK_STATUS_CANCEL.equals(task.getTaskStatus())) {
            throw new LogicException("工单处于取消状态");
        } else if (VMSystem.TASK_STATUS_FINISH.equals(task.getTaskStatus())) {
            throw new LogicException("工单已经处于完成状态");
        }
        //4.更新工单状态
        task.setTaskStatus(VMSystem.TASK_STATUS_FINISH);
        updateById(task);

        //5.发送售货机编号和工单类型
        sendMsg(task);

        return true;
    }

    /**
     * 发送消息
     */
    private void sendMsg(TaskEntity task) {
        Integer typeId = task.getProductTypeId();
        //1.如果工单为运维工单,发送消息到运维主题
        if (VMSystem.TASK_TYPE_DEPLOY.equals(typeId) || VMSystem.TASK_TYPE_REPAIR.equals(typeId) || VMSystem.TASK_TYPE_REVOKE.equals(typeId)) {
            TaskCompleteContract message = new TaskCompleteContract();
            message.setInnerCode(task.getInnerCode());
            message.setTaskType(typeId);
            try {
                mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, 2, JsonUtil.serialize(message));
            } catch (JsonProcessingException e) {
                log.error("发送消息失败", e);
            }
        }

        //2.如果工单为运运营工单,发送消息到运营主题
        if (VMSystem.TASK_TYPE_SUPPLY.equals(typeId)) {
            //查询补货信息
            List<TaskDetailsEntity> list = taskDetailsService
                    .list(Wrappers.<TaskDetailsEntity>lambdaQuery()
                            .eq(TaskDetailsEntity::getTaskId, task.getTaskId()));
            ArrayList<SupplyChannel> supplyChannelData = new ArrayList<>(list.size());
            //遍历集合转存转存补货数据
            list.stream().forEach((taskDetails -> {
                SupplyChannel channel = new SupplyChannel();
                channel.setChannelId(taskDetails.getChannelCode());
                channel.setCapacity(taskDetails.getExpectCapacity());
            }));
            //封装消息
            SupplyContract supplyContract = new SupplyContract();
            supplyContract.setInnerCode(task.getInnerCode());
            supplyContract.setSupplyData(supplyChannelData);
            //发送消息
            try {
                mqttProducer.send(TopicConfig.TASK_SUPPLY_TOPIC,2,JsonUtil.serialize(supplyChannelData));
            } catch (JsonProcessingException e) {
                log.error("下发补货工单失败");
                e.printStackTrace();
            }
        }
    }

    /**
     * 校验同一台设备是否有未完成同类型工单
     *
     * @param taskViewModel
     */
    private void checkTask(TaskViewModel taskViewModel) {
        List<TaskEntity> taskList = this.list(Wrappers.<TaskEntity>lambdaQuery()
                .eq(taskViewModel.getInnerCode() != null, TaskEntity::getInnerCode, taskViewModel.getInnerCode())
                .eq(TaskEntity::getCreateType, taskViewModel.getCreateType())
                .in(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_CREATE, VMSystem.TASK_STATUS_PROGRESS));
        if (!CollectionUtils.isEmpty(taskList)) {
            throw new LogicException("该设备还有未完成的同类型工单");
        }
    }

    /**
     * 保存工单详情表
     *
     * @param taskViewModel
     * @param task
     */
    private void saveTaskDetail(TaskViewModel taskViewModel, TaskEntity task) {
        List<TaskDetailsViewModel> detailsViewModels = taskViewModel.getDetails();
        List<TaskDetailsEntity> details = new ArrayList<>(detailsViewModels.size());
        if (!CollectionUtils.isEmpty(detailsViewModels)) {
            for (TaskDetailsViewModel detailsViewModel : detailsViewModels) {
                TaskDetailsEntity taskDetail = new TaskDetailsEntity();
                //属性拷贝
                BeanUtils.copyProperties(detailsViewModel, taskDetail);
                taskDetail.setTaskId(task.getTaskId());
                details.add(taskDetail);
            }
            //保存补货工单详情
            taskDetailsService.saveBatch(details);
        }
    }


    /**
     * 生成工单编号
     *
     * @return
     */
    private String generateTaskCode() {
        String value = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String key = "lkd.task.code";
        /*Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            redisTemplate.opsForValue().setIfAbsent(key, 0L, Duration.ofDays(1));
        }*/
        Long taskCode = redisTemplate.opsForValue().increment(key, 1);
        return value + String.format("%04d", taskCode);
    }


    /**
     * 检查售货机的状态
     *
     * @param taskViewModel
     * @param vmInfo
     */
    private void checkVmStatus(TaskViewModel taskViewModel, VmVO vmInfo) {
        if (vmInfo == null) {
            throw new LogicException("当前售货机不存在");
        }
        //如果是投放工单，状态为运营，抛出异常
        if (VMSystem.TASK_TYPE_DEPLOY.equals(taskViewModel.getProductType()) && VMSystem.VM_STATUS_RUNNING.equals(vmInfo.getVmStatus())) {
            throw new LogicException("售货机已在运行状态");
        }
        //如果是补货工单，状态不是运营状态，抛出异常
        if (VMSystem.TASK_TYPE_SUPPLY.equals(taskViewModel.getProductType()) && !VMSystem.VM_STATUS_RUNNING.equals(vmInfo.getVmStatus())) {
            throw new LogicException("设备未运行,不能补货");
        }
        //如果是撤机工单，状态不是运营状态，抛出异常
        if (VMSystem.TASK_TYPE_REVOKE.equals(taskViewModel.getProductType()) && !VMSystem.VM_STATUS_RUNNING.equals(vmInfo.getVmStatus())) {
            throw new LogicException("设备未运营,不能撤机");
        }
    }

}
